package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	"github.com/valyala/fasthttp"
	"net/url"
)

type GroupController struct{}

func (that *GroupController) Update(ctx *fasthttp.RequestCtx) {

	param := model.GroupUpdateParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	param.Gname, _ = url.QueryUnescape(param.Gname)
	param.Noted, _ = url.QueryUnescape(param.Noted)
	admin := session.AdminGet(ctx)
	adminifo, _ := model.GetAdminInfoById(admin["id"])
	err = model.GroupUpdate(param.ID, adminifo.GroupID, admin["name"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "succeed")
}

func (that *GroupController) Insert(ctx *fasthttp.RequestCtx) {

	param := model.GroupInsertParam{}
	err := json.Unmarshal(ctx.PostBody(), &param)
	if err != nil {

		helper.RetData(ctx, false, "参数错误")
		return
	}

	param.Gname, _ = url.QueryUnescape(param.Gname)
	param.Noted, _ = url.QueryUnescape(param.Noted)
	admin := session.AdminGet(ctx)
	adminifo, _ := model.GetAdminInfoById(admin["id"])
	// 新增权限信息
	err = model.GroupInsert(adminifo.GroupID, admin["name"], param)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "succeed")
}

/**
* @Description: 用户组列表获取
* @Author: carl
 */
func (that *GroupController) List(ctx *fasthttp.RequestCtx) {

	gid := string(ctx.QueryArgs().Peek("gid"))
	if gid != "" {
		if !helper.CtypeDigit(gid) {
			helper.RetData(ctx, false, helper.GroupIDErr)
			return
		}
	}

	admin := session.AdminGet(ctx)
	adminifo, _ := model.GetAdminInfoById(admin["id"])
	// 获取权限列表
	data, err := model.GroupList(gid, adminifo.GroupID)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	ctx.SetBody([]byte(data))
}
